﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Xml.Linq;
using System.Web.Services;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;
using KPIS.DBM;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_Option : System.Web.UI.Page
    {
        private IProject projectBLL;
        private string type;
        private IOptionTypeBLL optionType = new OptionTypeBLL();
        //double dSumWeight = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            type = Request.QueryString["type"].ToString();

            if (type.Length > 0)
            {
                projectBLL = Project_Factory.GetProjectFactory(type);
            }

            if (!IsPostBack)
            {
                lbOptionType.Text = Request.QueryString["optType"].ToString();
                int intOptionType = 0;
                int intHasChild = 0;

                if (int.TryParse(lbOptionType.Text, out intOptionType))
                {
                    intHasChild = optionType.Search(intOptionType)[0].HasChild;
                }

                if (!Object.Equals(Session["ProjectID"], null))
                {
                    lbProjectID.Text = Session["ProjectID"].ToString();
                    var dataTableA = projectBLL.GetDataProjectBySequence(lbProjectID.Text);
                    double sumAmount = Convert.ToDouble(dataTableA.Rows[0]["total_amount"] ==  DBNull.Value || dataTableA.Rows[0]["total_amount"] ==  null ? 0 : dataTableA.Rows[0]["total_amount"]);
                    lblSumAmount.Text = sumAmount.ToString("#,##0.00");
                }

                if (intHasChild != 2)
                {
                    LoadRepeater();
                    double dSumWeight = SumWeight(Repeater1);
                    lbSumWeight.Text = dSumWeight.ToString("#,##0.00");
                }
                else
                {
                    LoadTreeView();
                    tvOption_NodeCheck(null, null);
                }
            }
            else if (lbOptionType.Text != "3")
            {
                int intOptionType = 0;
                int intHasChild = 0;

                if (int.TryParse(lbOptionType.Text, out intOptionType))
                {
                    intHasChild = optionType.Search(intOptionType)[0].HasChild;
                }

                if (intHasChild != 2)
                {
                    LoadSubRepeater();
                }
            }
        }

        private void LoadRepeater()
        {
            divWeight.Visible = true;
            divTreeView.Visible = false;
            DataTable dtb = projectBLL.ListProjectOptionRepeater(lbProjectID.Text, null, lbOptionType.Text);
            Repeater1.DataSource = dtb;
            Repeater1.DataBind();

            LoadSubRepeater();
        }

        private void LoadSubRepeater()
        {
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                RepeaterItem item = Repeater1.Items[i];
                int nCount = Convert.ToInt32(((Label)item.FindControl("lblChildCount")).Text);

                if (nCount > 0)
                {
                    Panel PanelSub = (Panel)item.FindControl("PanelSub");
                    Label lblBgmOptionSeq = (Label)item.FindControl("lblBgmOptionSeq");
                    Repeater RepeaterNew = CloneControls(Repeater1);

                    DataTable dtb = projectBLL.ListProjectOptionRepeater(lbProjectID.Text, lblBgmOptionSeq.Text, lbOptionType.Text);
                    RepeaterNew.DataSource = dtb;
                    RepeaterNew.DataBind();

                    if (lbOptionType.Text == "1")
                    {
                        for (int j = 0; j < RepeaterNew.Items.Count; j++)
                        {
                            RepeaterItem itemNew = RepeaterNew.Items[j];
                            int nCountNew = Convert.ToInt32(((Label)itemNew.FindControl("lblChildCount")).Text);

                            if (nCountNew > 0)
                            {
                                Panel PanelSubNew = (Panel)itemNew.FindControl("PanelSub");
                                Label lblBgmOptionSeqNew = (Label)itemNew.FindControl("lblBgmOptionSeq");
                                Repeater RepeaterNew2 = CloneControls(RepeaterNew);

                                dtb = projectBLL.ListProjectOptionRepeater(lbProjectID.Text, lblBgmOptionSeqNew.Text, lbOptionType.Text);
                                RepeaterNew2.DataSource = dtb;
                                RepeaterNew2.DataBind();

                                PanelSubNew.Controls.Add(RepeaterNew2);
                                ((Panel)itemNew.FindControl("PanelItem")).BackColor = System.Drawing.Color.LemonChiffon;
                            }
                        }
                    }

                    PanelSub.Controls.Add(RepeaterNew);
                }

                if (lbOptionType.Text != "3")
                {
                    ((Panel)item.FindControl("PanelItem")).BackColor = System.Drawing.Color.Moccasin;
                }
            }
        }

        private void LoadTreeView()
        {
            divWeight.Visible = false;
            divTreeView.Visible = true;
            DataTable dtb = projectBLL.ListProjectOptionTreeView(lbProjectID.Text, lbOptionType.Text);
            tvOption.DataSource = dtb;
            tvOption.DataBind();

            tvOption.ExpandAllNodes();
            tvOption.UncheckAllNodes();

            CheckTreeView();
        }

        private void CheckTreeView()
        {
            DataTable dtb = projectBLL.ListProjectOption(lbProjectID.Text, lbOptionType.Text);

            foreach (DataRow dr in dtb.Rows)
            {
                string strBgmOptSeq = dr["bgm_option_seq"].ToString();
                foreach (RadTreeNode node in tvOption.Nodes)
                {
                    if (strBgmOptSeq == node.Value)
                    {
                        node.Checked = true;
                    }

                    CheckTreeView(node, strBgmOptSeq);
                }
            }
        }

        private void CheckTreeView(RadTreeNode _node, string strBgmOptSeq)
        {
            foreach (RadTreeNode node in _node.Nodes)
            {
                if (strBgmOptSeq == node.Value)
                {
                    node.Checked = true;
                }

                CheckTreeView(node, strBgmOptSeq);
            }
        }

        private Repeater CloneControls(Repeater o)
        {
            Type type = o.GetType();
            System.Reflection.PropertyInfo[] properties = type.GetProperties();
            Repeater retObject = (Repeater)type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);

            foreach (System.Reflection.PropertyInfo propertyInfo in properties)
            {
                if (propertyInfo.CanWrite)
                {
                    propertyInfo.SetValue(retObject, propertyInfo.GetValue(o, null), null);
                }
            }

            return retObject;
        }

        protected void txtWeight_TextChanged(object sender, EventArgs e)
        {
            RadNumericTextBox txtWeight = (RadNumericTextBox)sender;
            RepeaterItem item = (RepeaterItem)txtWeight.Parent.Parent;            
            Label lblAmount = (Label)item.FindControl("lblAmount");
            Panel PanelSub = (Panel)item.FindControl("PanelSub");
            int nChildCount = Convert.ToInt32(((Label)item.FindControl("lblChildCount")).Text);
            double dWeight = (txtWeight.Text.Length > 0 ? Convert.ToDouble(txtWeight.Text) : 0);
            double dSumAmount = (lblSumAmount.Text.Length > 0 ? Convert.ToDouble(lblSumAmount.Text) : 0);

            if (nChildCount > 0)
            {
                Repeater Repeater2 = (Repeater)item.FindControl("Repeater1");

                for (int i = 0; i < Repeater2.Items.Count; i++)
                {
                    RepeaterItem item2 = Repeater2.Items[i];
                    int nChildCount2 = Convert.ToInt32(((Label)item2.FindControl("lblChildCount")).Text);
                    Label lblAmount2 = (Label)item2.FindControl("lblAmount");
                    RadNumericTextBox txtWeight2 = (RadNumericTextBox)item2.FindControl("txtWeight");
                    double dWeight2 = dWeight / nChildCount;

                    if (nChildCount2 > 0)
                    {
                        Repeater Repeater3 = (Repeater)item2.FindControl("Repeater1");

                        for (int j = 0; j < Repeater3.Items.Count; j++)
                        {
                            RepeaterItem item3 = Repeater3.Items[j];
                            Label lblAmount3 = (Label)item3.FindControl("lblAmount");
                            RadNumericTextBox txtWeight3 = (RadNumericTextBox)item3.FindControl("txtWeight");
                            double dWeight3 = dWeight2 / nChildCount2;
                            txtWeight3.Text = dWeight3.ToString("#,##0.00");
                            lblAmount3.Text = ((dWeight3 * dSumAmount) / 100).ToString("#,##0.00");
                        }
                    }
                    else
                    {
                        txtWeight2.Text = dWeight2.ToString("#,##0.00");
                        lblAmount2.Text = ((dWeight2 * dSumAmount) / 100).ToString("#,##0.00");
                    }

                }
            }
            else
            {
                lblAmount.Text = ((dWeight * dSumAmount) / 100).ToString("#,##0.00");
            }

            double dSumWeight = SumWeight(Repeater1);
            lbSumWeight.Text = dSumWeight.ToString("#,##0.00");
            txtWeight.Focus();
        }

        protected double SumWeight(Repeater Repeater1)
        {
            double dSumWeight = 0;
            double dSumAmount = (lblSumAmount.Text.Length > 0 ? Convert.ToDouble(lblSumAmount.Text) : 0);

            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                RepeaterItem item = Repeater1.Items[i];
                RadNumericTextBox txtWeight = (RadNumericTextBox)item.FindControl("txtWeight");
                int nCount = Convert.ToInt32(((Label)item.FindControl("lblChildCount")).Text);
                double dWeight = 0;

                if (nCount > 0)
                {
                    Repeater Repeater2 = (Repeater)item.FindControl("Repeater1");
                    dWeight = SumWeight(Repeater2);
                    dSumWeight = dSumWeight + dWeight;
                    txtWeight.Text = dWeight.ToString("#,##0.00");
                    
                }
                else
                {
                    dWeight = (txtWeight.Text.Length > 0 ? Convert.ToDouble(txtWeight.Text) : 0);
                    dSumWeight = dSumWeight + dWeight;
                }

                Label lblAmount = (Label)item.FindControl("lblAmount");
                lblAmount.Text = ((dWeight * dSumAmount) / 100).ToString("#,##0.00");
            }

            return dSumWeight;
        }

        protected void btnSaveAddNewOpt_Click(object sender, EventArgs e)
        {
            double dSumWeight = (lbSumWeight.Text.Length > 0 ? Convert.ToDouble(lbSumWeight.Text) : 0);

            if (dSumWeight != 100)
            {
                RadAjaxManager1.Alert("น้ำหนักรวมทั้งหมดต้องเท่ากับ 100%");
                return;
            }

            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                RepeaterItem item = Repeater1.Items[i];
                int nCount = Convert.ToInt32(((Label)item.FindControl("lblChildCount")).Text);

                if (nCount > 0)
                {
                    Repeater Repeater2 = (Repeater)item.FindControl("Repeater1");

                    for (int j = 0; j < Repeater2.Items.Count; j++)
                    {
                        RepeaterItem item2 = Repeater2.Items[j];
                        int nCount2 = Convert.ToInt32(((Label)item2.FindControl("lblChildCount")).Text);

                        if (nCount2 > 0)
                        {
                            Repeater Repeater3 = (Repeater)item2.FindControl("Repeater1");

                            for (int k = 0; k < Repeater3.Items.Count; k++)
                            {
                                RepeaterItem item3 = Repeater3.Items[k];
                                SaveData(item3);
                            }
                        }
                        else
                        {
                            SaveData(item2);
                        }
                    }
                }
                else
                {
                    SaveData(item);
                }
            }
        }

        protected void btnSaveAddNewOpt2_Click(object sender, EventArgs e)
        {
            projectBLL.DeleteProjectOptionFromProjSeq(lbProjectID.Text, lbOptionType.Text);

            foreach (RadTreeNode node in tvOption.Nodes)
            {
                SaveData(node);
            }
            
        }

        protected void SaveData(RadTreeNode _node)
        {
            if (_node.Checked)
            {
                string strEmpSeq = new SsMng().GetUss(SsMng.SsUserType.EmpSeq);
                projectBLL.InsertProjectOption(lbProjectID.Text, null, null, _node.Value, strEmpSeq);
            }

            foreach (RadTreeNode node in _node.Nodes)
            {
                SaveData(node);
            }
        }

        protected void SaveData(RepeaterItem item)
        {
            Label lblBgmOptionSeq = (Label)item.FindControl("lblBgmOptionSeq");
            Label lblBgmProjOptSeq = (Label)item.FindControl("lblBgmProjOptSeq");
            RadNumericTextBox txtWeight = (RadNumericTextBox)item.FindControl("txtWeight");
            double dWeight = (txtWeight.Text.Length > 0 ? Convert.ToDouble(txtWeight.Text) : 0);

            string strEmpSeq = new SsMng().GetUss(SsMng.SsUserType.EmpSeq);

            if (dWeight > 0)
            {
                if (lblBgmProjOptSeq.Text.Length == 0)
                {
                    projectBLL.InsertProjectOption(lbProjectID.Text, null, dWeight, lblBgmOptionSeq.Text, strEmpSeq);
                }
                else
                {
                    projectBLL.UpdateProjectOption(lblBgmProjOptSeq.Text, null, dWeight, lblBgmOptionSeq.Text, strEmpSeq);
                }
            }
            else if (lblBgmProjOptSeq.Text.Length > 0)
            {
                projectBLL.DeleteProjectOption(lblBgmProjOptSeq.Text);
            }
        }

        protected void tvOption_NodeCheck(object sender, RadTreeNodeEventArgs e)
        {
            List<string> listOptionName = new List<string>();

            foreach (RadTreeNode node in tvOption.Nodes)
            {
                NodeCheck(node, listOptionName);
            }

            rptSample.DataSource = listOptionName;
            rptSample.DataBind();
        }

        private List<string> NodeCheck(RadTreeNode _node, List<string> listOptionName)
        {
            if (_node.Checked)
            {
                listOptionName.Add(_node.Text);
            }

            foreach (RadTreeNode node in _node.Nodes)
            {
                NodeCheck(node, listOptionName);
            }

            return listOptionName;
        }
    }
}
